package com.milorad.ads.data.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.TypedQuery;

import org.springframework.orm.jpa.JpaCallback;
import org.springframework.transaction.annotation.Transactional;

import com.milorad.ads.data.dao.interfaces.UserDao;
import com.milorad.ads.data.domain.User;

public class UserDaoImpl extends AbstractDaoJPAImpl<User> implements UserDao {

	public UserDaoImpl() {
		super(User.class);		
	}

	@Transactional
	public List<User> findAll() {
		return getJpaTemplate().execute(new JpaCallback<List<User>>() {
			public List<User> doInJpa(EntityManager em) throws PersistenceException {
				TypedQuery<User> query = em.createQuery("select u from User u", User.class);
				return query.getResultList();
			}
		});
	}

	@Transactional
	public int countAll() {
		return getJpaTemplate().execute(new JpaCallback<Integer>() {

			public Integer doInJpa(EntityManager em) throws PersistenceException {
				TypedQuery<Long> query = em.createQuery("select count(u) from User u", Long.class);
				return (query.getSingleResult()).intValue();
			}
		});
	}

	/**
	 * Finds user with specific username.
	 * 
	 * @param username - targeted username
	 */
	@Transactional
	public User findByUsername(final String username) {
		
		return getJpaTemplate().execute(new JpaCallback<User>() {
			public User doInJpa(EntityManager em) throws PersistenceException {
				TypedQuery<User> query = em.createQuery("select u from User u where u.username=:username", User.class);
				query.setParameter("username", username);
				
				List<User> users = query.getResultList();
				if (users.isEmpty()) {
					return null;
				} else {
					return users.iterator().next();
				}
			}
		});
	}
}